/**
 * 
 */
package com.appwx.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

/**
 * @author xiajun
 * 
 */
public class ImageLoader {

	private static final String TAG = ImageLoader.class.getSimpleName();
	private int stub_id;

	MemoryCache memoryCache = new MemoryCache();
	FileCache fileCache;

	/**
	 * 构建缓存文件目录
	 * 
	 * @param context
	 * @param cache_folder_name
	 * @param stub_id
	 */
	public ImageLoader(Context context, String cache_folder_name, int stub_id) {
		fileCache = new FileCache(context, cache_folder_name);
		this.stub_id = stub_id;
	}

	public void DisplayImage(String url, ImageView imageView) {
		// imageViews.put(imageView, url);
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
		} else {
			Log.i(TAG, "No memory cache for " + url);
			// queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
			DisplayImageTask imageTask = new DisplayImageTask(url, imageView);
			imageTask.execute(1);

		}

	}
	
	private Bitmap getBitmap(String url)
    {
        Log.i(TAG, "Try getting file cache for " + url);
        File f=fileCache.getFile(url);
        
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null) {
            return b;
        }
        
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }

	private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1=new FileInputStream(f);
            BitmapFactory.decodeStream(stream1,null,o);
            stream1.close();
            
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
            
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            FileInputStream stream2=new FileInputStream(f);
            Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
	
	class DisplayImageTask extends AsyncTask<Integer, Void, Bitmap> {

		private String url;
		private ImageView imageView;
		private Bitmap bmp;

		public DisplayImageTask(String url, ImageView imageView) {
			this.url = url;
			this.imageView = imageView;
		}

		protected Bitmap doInBackground(Integer... params) {
			try {

				bmp = getBitmap(url);

				if (bmp != null) {
					imageView.setImageBitmap(bmp);
				} else {
					imageView.setImageResource(stub_id);
				}

			} catch (Throwable th) {
				th.printStackTrace();
			}

			return bmp;
		}

		protected void onPostExecute(Bitmap bmp) {
			// if(imageViewReused(url,imageView)) { return null; }
		}
	}
}
